﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static MobileControlGuru.AutoTask.TaskJson;
using System.Web.UI;
using MobileControlGuru.Src;

namespace MobileControlGuru.AutoTask
{
    public partial class TaskList : BaseForm
    {
        // 定义一个事件，用于UI更新
        public event EventHandler<UpdateUIEventArgs> UIUpdateEvent;

        private static TaskList instance;
        // 定义委托
        delegate void UpdateUIControlHandler(string taskitemID);
        public TaskList()
        {
            InitializeComponent();
            // 订阅UI更新事件
            this.UIUpdateEvent += FormTaskList_UIUpdateEvent;
        }
        // UI更新事件的处理程序
        private void FormTaskList_UIUpdateEvent(object sender, UpdateUIEventArgs e)
        {
            // 确保在UI线程上执行
            if (this.InvokeRequired)
            {
                this.Invoke(new EventHandler<UpdateUIEventArgs>(FormTaskList_UIUpdateEvent), sender, e);
                return;
            }

            // 更新labelTaskName的内容
            labelTaskName.Text = e.Message;
        }

        // 模拟的后台作业触发UI更新
        // 注意：在实际应用中，这部分代码可能位于Quartz.NET作业或其他后台线程中
        private void SimulateBackgroundJob()
        {
            // 假设这是从后台作业中获取的文本
            string message = "从后台作业接收的消息";

            // 触发UI更新事件
            OnUIUpdate(message);
        }

        // 受保护的虚拟方法，用于触发UI更新事件
        public virtual void OnUIUpdate(string message)
        {
            UIUpdateEvent?.Invoke(this, new UpdateUIEventArgs(message));
        }
        public static TaskList GetInstance()
        {
            if (instance == null || instance.IsDisposed)
            {
                instance = new TaskList();
            }
            return instance;
        }

        private void TaskList_Load(object sender, EventArgs e)
        {
            LoadingHelper.ShowLoadingScreen(this);//显示

            var t1 = Task.Run(() =>
              {
                  Init();
              });


        }

        public void Init()
        {

            List<TaskInfo> taskInfos = TaskJson.LoadJsonData();
            this.RefreshTaskList();

        }
        public void RefreshTaskList()
        {
            if (this.InvokeRequired)
            {
                //TaskJson.LoadJsonData();
                // 在 UI 线程中更新界面
                this.Invoke((MethodInvoker)delegate
            {

                InitTaksListControl();

            });
            }
            else
            {
                // 更新 UI 控件

                InitTaksListControl();
            }

        }
        void InitTaksListControl()
        {
            try
            {
                // 在这里更新 UI 组件
                //获取所有任务列表
                List<TaskInfo> tasks = TaskJson.Instance.tasks;


                lblTaskCount.Text = tasks.Count().ToString();
                // 使用 LINQ 对列表进行排序
                var sortedTaskInfos = tasks
                    .Where(ti => ti.StartDeteTime.HasValue) // 可选：仅包含有 StartDateTime 的项
                    .OrderBy(ti => ti.StartDeteTime.Value) // 按 StartDateTime 升序排序
                    .ToList(); // 将结果转换回 List<TaskInfo>
                if (sortedTaskInfos.Count == 0)
                {
                    sortedTaskInfos = tasks;
                }
                this.flowLayoutPanel1.Controls.Clear();
                int i = 0;
                foreach (var task in sortedTaskInfos)
                {
                    i++;
                    var item = new TaskShowItem(task);
                    item.lblNo.Text = i.ToString();
                    item.taskList = this;
                    item.Tag = task;
                    //switch (task.State)
                    //{

                    //    case TaskJson.TaskStateEnum.notrun:
                    //        item.lblState.Text = "未开始运行";
                    //        break;
                    //    case TaskJson.TaskStateEnum.run:
                    //        item.lblState.Text = "运行中";
                    //        break;
                    //    case TaskJson.TaskStateEnum.done:
                    //        item.lblState.Text = "已完成";
                    //        break;
                    //    default:
                    //        break;
                    //}
                    if (TaskManager.Instance._scheduledJobKey != null)
                    {
                        bool isContains = TaskManager.Instance._scheduledJobKey.Contains(task.Name);
                        item.btnTaskRun.Enabled = !isContains;
                    }

                    item.lblDateTime.Text = task.StartDeteTime.ToString() + "/" + task.EndDeteTime.ToString();
                    this.flowLayoutPanel1.Controls.Add(item);
                }


                inputNumberTask.Text = "20";
                inputNumberTask.Value = 20;
                // 更新UI，但需要从UI线程调用
                this.Invoke((MethodInvoker)delegate
                {
                    LoadingHelper.CloseForm();//关闭
                });
            }
            catch (Exception ex)
            {// 处理异常或记录日志
                Tools.LogHelper.Error(ex.Message);
                MessageBox.Show("发生异常: " + ex.Message);
                // 更新UI，但需要从UI线程调用
                this.Invoke((MethodInvoker)delegate
                {
                    LoadingHelper.CloseForm();//关闭
                });
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {

            TaskEdit diglog = new TaskEdit();
            diglog.comboBoxType.SelectedIndex = 1;
            diglog.StartPosition = FormStartPosition.CenterParent;
            diglog.FormClosed += EditFormClosed;
            diglog.Show(this);
        }

        private void EditFormClosed(object sender, FormClosedEventArgs e)
        {
            Init();
        }

        public void ShowEdit(TaskJson.TaskInfo taskinfo)
        {
            TaskEdit diglog = new TaskEdit(taskinfo);
            diglog.StartPosition = FormStartPosition.CenterParent;
            diglog.FormClosed += EditFormClosed;
            diglog.Show(this);

        }

        public void DelTask(int id)
        {

            TaskJson.DelTask(id);
            Init();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {


            // 序列化数据到JSON字符串
            string jsonData = JsonConvert.SerializeObject(Instance.tasks, Formatting.Indented);
            // 创建SaveFileDialog实例并配置
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "JSON (*.json)|*.json|所有文件 (*.*)|*.*";
            saveFileDialog.Title = "导出数据";
            saveFileDialog.FileName = $"任务JSON_{DateTime.Now.ToString("yyyyMMddHHmmss")}"; // 默认文件名

            // 显示保存对话框并获取用户选择
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = saveFileDialog.FileName;

                try
                {
                    //TaskJson.LoadJsonData();
                    //TaskJson.SaveJsonData(filePath);
                    File.WriteAllText(saveFileDialog.FileName, jsonData);
                    MessageBox.Show("数据导出成功！");
                }
                catch (Exception ex)
                {
                    // 处理文件写入过程中的异常
                    MessageBox.Show($"导出失败：{ex.Message}");
                }
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            // 创建并配置OpenFileDialog
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "JSON files (*.json)|*.json";
                openFileDialog.Title = "Open JSON File";

                // 显示OpenFileDialog
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = openFileDialog.FileName;

                    try
                    {
                        // 读取JSON文件内容
                        string jsonContent = File.ReadAllText(filePath);


                        //MessageBox.Show("JSON文件格式正确。");
                        // 进一步处理jsonObject...
                        LoadingHelper.ShowLoadingScreen(this);//显示
                        List<TaskInfo> tasks = JsonConvert.DeserializeObject<List<TaskInfo>>(jsonContent);
                        TaskJson.AddMultiTask(tasks);
                        //TaskJson.SaveJsonData();



                        this.RefreshTaskList();
                    }
                    catch (JsonReaderException jsonEx)
                    {
                        // 捕获JSON格式错误
                        MessageBox.Show($"JSON格式错误：{jsonEx.Message}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        // 捕获其他错误
                        MessageBox.Show($"读取文件时发生错误：{ex.Message}");
                    }
                }
            }
        }

        // 执行更新 UserControl 的方法
        public void UpdateUserControl(string taskitemID)
        {
            if (flowLayoutPanel1.InvokeRequired)
            {
                UpdateUIControlHandler handler = UpdateUserControl;
                flowLayoutPanel1.Invoke(handler, taskitemID);
            }
            else
            {

                //flowLayoutPanel1.UpdateUI(message);
                //foreach (TaskShowItem control in this.flowLayoutPanel1.Controls)
                //{
                //    if (taskitemID == control.taskInfo.Name)
                //    {
                //        control.btnTaskRun.Enabled = false;
                //        control.lblState.Text = "kaishi ";
                //    }




                //}
            }
        }

        private void btnAllStart_Click(object sender, EventArgs e)
        {
            TaskManager tm = TaskManager.Instance;
            if (!string.IsNullOrEmpty(inputNumberTask.Text))
                tm.MaxConcurrentTasks = Convert.ToInt32(inputNumberTask.Text);
            tm.MultiJobStart(TaskJson.Instance.tasks);

        }

        private void btnAllStop_Click(object sender, EventArgs e)
        {
            TaskManager tm = TaskManager.Instance;
            tm.MultiJobEnd(TaskJson.Instance.tasks);
            this.labelTaskName.Text = "0";
            foreach (TaskShowItem control in this.flowLayoutPanel1.Controls)
            {

                control.btnTaskRun.Enabled = true;

            }
        }

        private void btnMultiAddTask_Click(object sender, EventArgs e)
        {
            ShowEditMulti(null);
        }
        public void ShowEditMulti(TaskJson.TaskInfo taskinfo)
        {
            TaskEdit diglog = new TaskEdit(taskinfo);
            diglog.comboBoxType.SelectedIndex = 0;

            diglog.StartPosition = FormStartPosition.CenterParent;
            diglog.FormClosed += EditFormClosed;
            diglog.Show(this);

        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            this.btnClear.Text = "正在删除...";
            var t = Task.Run(() =>
            {
                TaskJson.ClearTask();
            });
            //LoadingHelper.ShowLoadingScreen(this);//显示
            Task.WaitAll(t);
            Init();
            this.btnClear.Text = "清空";
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Init();
        }
        #region 批量设置操作带变量
        private void btnMultiTaskTemp_Click(object sender, EventArgs e)
        {
            MultiTaskEdit multiTaskEdit = new MultiTaskEdit();
            multiTaskEdit.FormClosed += EditFormClosed;
            multiTaskEdit.Show(this);
        }
        #endregion



    }
}
